# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 系统API
"""

from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.api.system import bp
from app.models import SystemConfig, BasicInfoConfig, AgreementContent
from app import db
from app.utils.helpers import success_response, error_response
from app.utils.decorators import admin_required, permission_required
from datetime import datetime


@bp.route('/config', methods=['GET'])
def get_system_config():
    """获取系统配置"""
    try:
        # 获取基础配置
        configs = SystemConfig.query.filter_by(is_active=True).all()
        
        config_data = {}
        for config in configs:
            if config.config_type.value == 'basic':
                config_data['basic'] = config_data.get('basic', {})
                config_data['basic'][config.key] = config.value
            elif config.config_type.value == 'feature':
                config_data['features'] = config_data.get('features', {})
                config_data['features'][config.key] = config.value
            elif config.config_type.value == 'ui':
                config_data['ui'] = config_data.get('ui', {})
                config_data['ui'][config.key] = config.value
        
        # 设置默认值
        if 'basic' not in config_data:
            config_data['basic'] = {}
        
        config_data['basic'].setdefault('site_name', '心理健康测评系统')
        config_data['basic'].setdefault('site_description', '专业的心理健康测评平台')
        config_data['basic'].setdefault('contact_email', 'support@example.com')
        config_data['basic'].setdefault('contact_phone', '400-000-0000')
        
        if 'features' not in config_data:
            config_data['features'] = {}
        
        config_data['features'].setdefault('registration_enabled', 'true')
        config_data['features'].setdefault('email_verification_required', 'false')
        config_data['features'].setdefault('phone_verification_required', 'false')
        config_data['features'].setdefault('guest_assessment_enabled', 'true')
        
        return success_response('获取系统配置成功', config_data)
        
    except Exception as e:
        current_app.logger.error(f'获取系统配置失败: {str(e)}')
        return error_response('获取系统配置失败')


@bp.route('/basic-info-config', methods=['GET'])
def get_basic_info_config():
    """获取基本信息配置"""
    try:
        configs = BasicInfoConfig.query.filter_by(status='active').order_by(
            BasicInfoConfig.sort_order.asc()
        ).all()
        
        config_list = []
        for config in configs:
            config_data = {
                'id': config.id,
                'field_name': config.field_name,
                'field_label': config.field_label,
                'field_type': config.field_type.value,
                'is_required': config.is_required,
                'placeholder': config.placeholder,
                'help_text': config.help_text,
                'sort_order': config.sort_order,
                'options': [{
                    'value': option.value,
                    'label': option.label
                } for option in config.options] if config.options else [],
                'validation_rules': [{
                    'type': rule.validation_type.value,
                    'value': rule.value,
                    'message': rule.message
                } for rule in config.validation_rules] if config.validation_rules else []
            }
            config_list.append(config_data)
        
        return success_response('获取基本信息配置成功', config_list)
        
    except Exception as e:
        current_app.logger.error(f'获取基本信息配置失败: {str(e)}')
        return error_response('获取基本信息配置失败')


@bp.route('/agreements', methods=['GET'])
def get_agreements():
    """获取协议内容"""
    try:
        agreement_type = request.args.get('type', 'user_agreement')
        
        agreement = AgreementContent.query.filter_by(
            agreement_type=agreement_type,
            is_active=True
        ).first()
        
        if not agreement:
            # 返回默认协议内容
            default_content = {
                'user_agreement': {
                    'title': '用户协议',
                    'content': '这里是用户协议的默认内容...',
                    'version': '1.0'
                },
                'privacy_policy': {
                    'title': '隐私政策',
                    'content': '这里是隐私政策的默认内容...',
                    'version': '1.0'
                }
            }
            
            content = default_content.get(agreement_type, {
                'title': '协议',
                'content': '协议内容暂未配置',
                'version': '1.0'
            })
        else:
            content = {
                'title': agreement.title,
                'content': agreement.content,
                'version': agreement.version,
                'updated_at': agreement.updated_at.isoformat() if agreement.updated_at else None
            }
        
        return success_response('获取协议内容成功', content)
        
    except Exception as e:
        current_app.logger.error(f'获取协议内容失败: {str(e)}')
        return error_response('获取协议内容失败')


@bp.route('/version', methods=['GET'])
def get_system_version():
    """获取系统版本信息"""
    try:
        version_info = {
            'version': '1.0.0',
            'build_date': '2024-01-01',
            'environment': current_app.config.get('ENV', 'production'),
            'api_version': 'v1',
            'features': {
                'user_registration': True,
                'email_verification': False,
                'phone_verification': False,
                'guest_assessment': True,
                'membership_system': True,
                'admin_panel': True
            }
        }
        
        return success_response('获取版本信息成功', version_info)
        
    except Exception as e:
        current_app.logger.error(f'获取版本信息失败: {str(e)}')
        return error_response('获取版本信息失败')


@bp.route('/health', methods=['GET'])
def health_check():
    """系统健康检查"""
    try:
        # 检查数据库连接
        db.session.execute('SELECT 1')
        
        # 检查Redis连接（如果配置了）
        redis_status = 'ok'
        try:
            from app import redis_client
            if redis_client:
                redis_client.ping()
        except Exception:
            redis_status = 'error'
        
        health_data = {
            'status': 'healthy',
            'timestamp': datetime.utcnow().isoformat(),
            'services': {
                'database': 'ok',
                'redis': redis_status
            },
            'uptime': '运行正常'
        }
        
        return success_response('系统健康', health_data)
        
    except Exception as e:
        current_app.logger.error(f'健康检查失败: {str(e)}')
        return error_response('系统异常', {
            'status': 'unhealthy',
            'timestamp': datetime.utcnow().isoformat(),
            'error': str(e)
        })


@bp.route('/stats', methods=['GET'])
def get_system_stats():
    """获取系统统计信息"""
    try:
        from app.models import User, Scale, Assessment
        from sqlalchemy import func
        
        # 基础统计
        total_users = User.query.count()
        total_scales = Scale.query.count()
        total_assessments = Assessment.query.count()
        
        # 今日统计
        today = datetime.utcnow().date()
        today_users = User.query.filter(
            func.date(User.created_at) == today
        ).count()
        
        today_assessments = Assessment.query.filter(
            func.date(Assessment.created_at) == today
        ).count()
        
        # 活跃用户统计（最近7天有测评记录）
        from datetime import timedelta
        seven_days_ago = datetime.utcnow() - timedelta(days=7)
        active_users = db.session.query(Assessment.user_id).filter(
            Assessment.created_at >= seven_days_ago
        ).distinct().count()
        
        stats = {
            'totals': {
                'users': total_users,
                'scales': total_scales,
                'assessments': total_assessments
            },
            'today': {
                'new_users': today_users,
                'assessments': today_assessments
            },
            'active': {
                'users_7d': active_users
            }
        }
        
        return success_response('获取统计信息成功', stats)
        
    except Exception as e:
        current_app.logger.error(f'获取统计信息失败: {str(e)}')
        return error_response('获取统计信息失败')


# 管理员专用接口

@bp.route('/config', methods=['PUT'])
@jwt_required()
@admin_required
@permission_required('system.config')
def update_system_config():
    """更新系统配置"""
    try:
        data = request.get_json()
        config_type = data.get('config_type')
        configs = data.get('configs', {})
        
        if not config_type or not configs:
            return error_response('请提供配置类型和配置数据')
        
        from app.models.config import ConfigType
        try:
            config_type_enum = ConfigType(config_type)
        except ValueError:
            return error_response('配置类型不正确')
        
        # 更新配置
        for key, value in configs.items():
            config = SystemConfig.query.filter_by(
                config_type=config_type_enum,
                key=key
            ).first()
            
            if config:
                config.value = str(value)
                config.updated_at = datetime.utcnow()
            else:
                config = SystemConfig(
                    config_type=config_type_enum,
                    key=key,
                    value=str(value),
                    description=f'{key}配置'
                )
                db.session.add(config)
        
        db.session.commit()
        
        return success_response('更新系统配置成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新系统配置失败: {str(e)}')
        return error_response('更新系统配置失败')


@bp.route('/agreements', methods=['PUT'])
@jwt_required()
@admin_required
@permission_required('system.config')
def update_agreement():
    """更新协议内容"""
    try:
        data = request.get_json()
        agreement_type = data.get('agreement_type')
        title = data.get('title')
        content = data.get('content')
        
        if not all([agreement_type, title, content]):
            return error_response('请提供完整的协议信息')
        
        agreement = AgreementContent.query.filter_by(
            agreement_type=agreement_type
        ).first()
        
        if agreement:
            agreement.title = title
            agreement.content = content
            agreement.version = str(float(agreement.version) + 0.1)
            agreement.updated_at = datetime.utcnow()
        else:
            agreement = AgreementContent(
                agreement_type=agreement_type,
                title=title,
                content=content,
                version='1.0'
            )
            db.session.add(agreement)
        
        db.session.commit()
        
        return success_response('更新协议内容成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新协议内容失败: {str(e)}')
        return error_response('更新协议内容失败')


@bp.route('/maintenance', methods=['POST'])
@jwt_required()
@admin_required
@permission_required('system.maintenance')
def toggle_maintenance_mode():
    """切换维护模式"""
    try:
        data = request.get_json()
        enabled = data.get('enabled', False)
        message = data.get('message', '系统正在维护中，请稍后再试')
        
        # 更新维护模式配置
        config = SystemConfig.query.filter_by(
            config_type='basic',
            key='maintenance_mode'
        ).first()
        
        if config:
            config.value = 'true' if enabled else 'false'
        else:
            config = SystemConfig(
                config_type='basic',
                key='maintenance_mode',
                value='true' if enabled else 'false',
                description='维护模式开关'
            )
            db.session.add(config)
        
        # 更新维护消息
        message_config = SystemConfig.query.filter_by(
            config_type='basic',
            key='maintenance_message'
        ).first()
        
        if message_config:
            message_config.value = message
        else:
            message_config = SystemConfig(
                config_type='basic',
                key='maintenance_message',
                value=message,
                description='维护模式消息'
            )
            db.session.add(message_config)
        
        db.session.commit()
        
        return success_response(
            f'维护模式已{"开启" if enabled else "关闭"}',
            {'enabled': enabled, 'message': message}
        )
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'切换维护模式失败: {str(e)}')
        return error_response('切换维护模式失败')